import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SolutionInterview16_19 {

    int[] dx={1,0,-1,0,1,1,-1,-1};
    int[] dy={0,1,0,-1,1,-1,1,-1};

    public int[] pondSizes(int[][] land) {
        List<Integer> list=new ArrayList<>();
        int[][] visit=new int[land.length][land[0].length];
        for (int i=0;i<land.length;i++){
            for (int j=0;j<land[0].length;j++){
                if (visit[i][j]==0 && land[i][j]==0){
                    list.add(dfs(i,j,visit,land));
                }
            }
        }
        list.sort(Comparator.comparingInt(a -> a));
        int[] ans=new int[list.size()];
        for (int i=0;i<list.size();i++){
            ans[i]=list.get(i);
        }
        return ans;
    }

    private int dfs(int x, int y, int[][] visit, int[][] land) {
        if (!(x>=0 && x<visit.length && y>=0 && y<visit[0].length)){
            return 0;
        }
        if (visit[x][y]==1 || land[x][y]>0){
            return 0;
        }
        visit[x][y]=1;
        int ans=1;
        for (int i = 0; i < 8; i++) {
            ans+=dfs(x+dx[i],y+dy[i],visit,land);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new SolutionInterview16_19().pondSizes(new int[][]{{0, 2, 1, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}, {0, 1, 0, 1}})));
    }
}
